import { Card, Input, Col, Row, Button, Form, Modal, Table, Switch, Select } from 'antd'
import React, { useEffect, useRef, useState } from 'react'
import server from '../../utils/request'
import { EditOutlined, DeleteOutlined, SettingOutlined } from "@ant-design/icons"
const { Search } = Input;
function UserManage() {
    const { Option } = Select;
    const formRef = useRef()
    const [updateId, setupdateId] = useState(null)  // 修改ID和 分配角色ID
    const [editform] = Form.useForm();
    const [RoleId,setRoleId]=useState(null)
    const [roleVisible, setroleVisible] = useState(false)
    const [addFormVisible, setaddFormVisible] = useState(false)   // 添加框
    const [updateFormVisible, setaupdateFormVisible] = useState(false)  //修改框
    const [pagenum, setpagenum] = useState(1)  // 当前页码
    const [pagesize, setpagesize] = useState(1000)  // 每页条数
    const [dataList, setdataList] = useState([])  // 
    const [total, settotal] = useState(0)  //  总条数
    const [roleData, setroleData] = useState({})
    const [rolesList, setrolesList] = useState([])
    // 搜索
    const onSearch = value => console.log(value);
    // 开关切换状态
    const onChangeSwitch = async (mg_state, id) => {
        const res = await server.put(`/users/${id}/state/${!mg_state}`)
        dataList.filter(item => item.id === id)[0].mg_state = !mg_state
        setdataList([...dataList])

    }
    const columns = [
        {
            title: "#",
            dataIndex: "id"
        },
        {
            title: "姓名",
            dataIndex: "username"
        },
        {
            title: "邮箱",
            dataIndex: "email"
        },
        {
            title: "电话",
            dataIndex: "mobile"
        },
        {
            title: "角色",
            dataIndex: "role_name"
        },
        {
            title: "状态",
            dataIndex: "mg_state",
            render: (mg_state, item) => {
                return <Switch defaultChecked checked={mg_state} onChange={() => onChangeSwitch(mg_state, item.id)} />
            }
        },
        {
            title: "操作",
            render: (item) => {
                return <div>
                    <Button icon={<EditOutlined />} onClick={() => { editForm(item) }}></Button>
                    <Button icon={<DeleteOutlined />} onClick={() => del(item.id)} ></Button>
                    <Button icon={<SettingOutlined />} onClick={() => roles(item)} ></Button>
                </div>
            }
        }
    ]
    // 修改框开关
    const editForm = (item) => {
        // EditformRef.current.setFieldsValue(item)
        setupdateId(item.id)
        setaupdateFormVisible(!updateFormVisible)

        editform.setFieldsValue(item)

    }
    // 分页配置
    const changePage = (pagenum, pagesize) => {
        setpagenum(pagenum)
        setpagesize(pagesize)
    }

    const randomString = (e) => {
        e = e || 32;
        var t = "ABCDEFGHJKMNPQRSTWXY",
            a = t.length,
            n = "";
        for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
        return n
    }
    // Form表单执行添加操作
    const onFinish = async (values) => {

        // for (let a = 0; a < 500; a++) {

        //     let resa = randomString()
        //     let aa = {
        //         username: a+'我是你大哥焦兵洋' + resa+"别删老子数据",
        //         password: resa,
        //         email: resa,
        //         mobile: resa
        //     }
        //     const res = await server.post('/users', aa)
        //     formRef.current.resetFields()
        // }
        const res = await server.post('/users', values)

        formRef.current.resetFields()
        getList()
        setaddFormVisible(!addFormVisible)

    };

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    // 获取基本数据
    const getList = async () => {
        const res = await server.get(`/users?pagenum=${pagenum}&pagesize=${pagesize}`)
        // console.log(res.data.users);
        setdataList(res.data.users)
        settotal(res.data.total)
    }
    // 删除数据
    const del = (id) => {
        server.delete(`/users/${id}`)
        // dataList.filter(item => item.id === id)

        dataList.splice(dataList.findIndex(item => item.id === id), 1)
        setdataList([...dataList])
    }
    // 修改成功框  (有点问题)
    const onFinishUpdate = (value) => {
        setaupdateFormVisible(!updateFormVisible)
        dataList.filter(item => item.id === updateId)[0].email = value.email
        dataList.filter(item => item.id === updateId)[0].mobile = value.mobile
        // console.log(dataList.filter(item=>item.id===updateId));
        setdataList([...dataList])
        server.put(`users/${updateId}`, {
            email: value.email,
            mobile: value.mobile
        })
    }
    // 修改失败框
    const onFinishFailedupdate = () => {

    }
    // 分配角色框
    const roles = async (item) => {
        setroleVisible(true)
        setroleData(item)
        
        const rol = await server.get("/roles")
        // console.log(rol);
        setrolesList(rol.data)
    }
    // 分配角色多选框
    const onGenderChange = (e) => {
        console.log(e,1111);
        setRoleId(e)
    }   
    const fenpei=async()=>{
        setroleVisible(!roleVisible)
        
        const res = await server.put(`/users/${roleData.id}`,{
            RoleId
        })
        console.log(res);
        // console.log(roleData,'该用户');
    }
    useEffect(() => {
        getList()
    }, [])
    return (

        <Card>
            <Modal
                title="分配角色"
                centered
                visible={roleVisible}
                onOk={fenpei}
                onCancel={() => setroleVisible(false)}
                width={800}
            >
                <p>当前的用户：{roleData.username}</p>
                <p>当前的角色：{roleData.role_name}</p>
                <Select
                    placeholder="Select a option and change input text above"
                    onChange={onGenderChange}
                    allowClear
                    width={150}
                >
                    {
                        rolesList.map(item => {
                            return <Option  key={item.id} value={item.id}>{item.roleName}</Option>
                        })
                    }
                </Select>
            </Modal>
            <Row style={{ margin: 12 }}>
                <Col span={8}>
                    <Search placeholder="input search text" onSearch={onSearch} style={{ marginRight: 12, width: 200 }} />
                    <Button onClick={() => { setaddFormVisible(!addFormVisible) }} type="primary">添加用户</Button>
                </Col>
            </Row>
            <Row>
                <Col span={24}>
                    <Table dataSource={dataList} columns={columns} rowKey={(item) => item.id}
                        pagination={{
                            current: pagenum,
                            pageSize: 5,
                            total: total,
                            onChange: changePage,
                            pageSizeOptions: [2, 5, 10]
                        }}
                    />

                </Col>
            </Row>

            <Modal
                title="Title"
                visible={updateFormVisible}
                // onOk={handleOk}
                onCancel={() => setaupdateFormVisible(!updateFormVisible)}
                footer={null}
            >
                <Form
                    // ref={EditformRef}
                    form={editform}
                    name="basic"
                    labelCol={{
                        span: 8,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={onFinishUpdate}
                    onFinishFailed={onFinishFailedupdate}
                    autoComplete="off"
                >
                    <Form.Item
                        label="Username"
                        name="username"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your username!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="Email"
                        name="email"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your email!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="Mobile"
                        name="mobile"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your mobile!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            offset: 16,
                            span: 16,
                        }}
                    >
                        <Button style={{ margin: 5 }} onClick={() => { setaupdateFormVisible(!updateFormVisible) }}>取消</Button>
                        <Button style={{ margin: 5 }} type="primary" htmlType="submit">
                            确认
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>

            {/*添加数据表单 */}
            <Modal
                title="Title"
                visible={addFormVisible}
                // onOk={handleOk}
                onCancel={() => setaddFormVisible(!addFormVisible)}
                footer={null}
            >
                <Form
                    ref={formRef}
                    name="basic"
                    labelCol={{
                        span: 8,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        label="Username"
                        name="username"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your username!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="Password"
                        name="password"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your password!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="Email"
                        name="email"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your email!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="Mobile"
                        name="mobile"
                        rules={[
                            {
                                required: true,
                                message: 'Please input your mobile!',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        wrapperCol={{
                            offset: 16,
                            span: 16,
                        }}
                    >
                        <Button style={{ margin: 5 }} onClick={() => { setaddFormVisible(!addFormVisible) }}>取消</Button>
                        <Button style={{ margin: 5 }} type="primary" htmlType="submit">
                            确认
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>

        </Card>


    )
}

export default UserManage
